import { defineStore } from 'pinia'
import { type ArticleDTO, initArticleDTO } from '@/request/api/article'
import type { ClassifyEnum } from '@/enum'
import { type ClassifyLabelVO, getClassifyLabelsTreeApi } from '@/request/api/classify'
import type { ResultType } from '@/type/type'
import type { LabelVO } from '@/request/api/label'
import { getRoleListApi, type RoleVO } from '@/request/api/role'
import { type CommentDTO, initCommentDTO } from '@/request/api/comment'

// 持久化存储
export const useTemporaryStore = defineStore(
  'temporary',
  () => {
    const article = ref<ArticleDTO>({
      id: undefined,
      labelId: undefined,
      title: undefined,
      cover: undefined,
      content: undefined,
      likeCount: undefined,
      viewCount: undefined,
      hasVideo: undefined,
      videoUrl: undefined,
      tips: undefined,
      isRecommend: undefined,
      isComment: undefined,
      origin: undefined,
      status: undefined,
      password: undefined
    })
    // 记录文章上传文件的地址
    const urls = ref<string[]>([])

    const initArticle = () => {
      article.value = initArticleDTO()
      urls.value = []
      upload.value.init()
    }

    // 评论数据共享
    const comment = ref<CommentDTO>(initCommentDTO())
    // 保存评论回复状态
    const commentReply = ref<{
      parentName: undefined | string
      isReply: boolean
    }>({
      parentName: undefined,
      isReply: false
    })

    const initComment = () => {
      // 重置评论数据, 保留sourceId
      const sourceId = comment.value.sourceId
      comment.value = initCommentDTO()
      comment.value.sourceId = sourceId
      commentReply.value = {
        parentName: undefined,
        isReply: false
      }
      upload.value.init()
    }

    // 表单数据共享
    const form = reactive<{
      classifyId: number
      labelId: number
      roleId: number
    }>({
      classifyId: -1,
      labelId: -1,
      roleId: -1
    })

    // 分类，标签数据共享
    const classifyMap = reactive<Map<ClassifyEnum, ClassifyLabelVO[]>>(new Map())
    const labelMap = reactive<Map<number, LabelVO[]>>(new Map())
    const getClassifyList = async (type: ClassifyEnum) => {
      const classifyList = classifyMap.get(type)
      if (classifyList && classifyList.length) {
        return classifyList
      } else {
        await getClassifyLabelsTreeApi(type).then((res: ResultType<ClassifyLabelVO[]>) => {
          classifyMap.set(type, res.data)
          for (let i = 0; i < res.data.length; i++) {
            labelMap.set(res.data[i].id, res.data[i].labels)
          }
        })
        return classifyMap.get(type) || []
      }
    }

    const getLabelList = (id: number): LabelVO[] => {
      return labelMap.get(id) || []
    }

    // 角色数据
    const roleList = ref<RoleVO[]>([])
    getRoleListApi().then((res: ResultType<RoleVO[]>) => {
      if (res.code === 200) {
        roleList.value = res.data
        if (roleList.value.length > 0) {
          form.roleId = roleList.value[0].id
        }
      }
    })

    const upload = ref<{
      formData: FormData
      uploadRef: any
      urls: any
      init: () => void
    }>({
      formData: new FormData(),
      uploadRef: null,
      // 修改时回显图片地址
      urls: [],
      init: () => {
        upload.value.formData = new FormData()
        upload.value.urls = []
        if (upload.value.uploadRef) {
          upload.value.uploadRef.clearFiles()
        }
      }
    })

    const setUploadUrls = (paths: string[]) => {
      upload.value.urls = []
      for (let i = 0; i < paths.length; i++) {
        const str = {
          url: paths[i]
        }
        upload.value.urls.push(str)
      }
    }

    return {
      form,
      article,
      initArticle,
      urls,
      comment,
      commentReply,
      initComment,
      roleList,
      getClassifyList,
      getLabelList,
      upload,
      setUploadUrls
    }
  },
  {
    persist: {
      key: 'temporary',
      paths: ['article', 'urls'],
      afterRestore: ({ store }) => {}
    }
  }
)
